package com.example.serviceweb.filter;

import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.WeakHashMap;


@Activate(group = {CommonConstants.CONSUMER})
public class TransportIPFilter implements Filter {
    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        String methodName = invocation.getMethodName();
        if(methodName.equals("sayHello") || methodName.equals("sayHello2")) {
            HttpServletRequest req = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            Map<String, String> attachments = new WeakHashMap<>(8);
            attachments.put("ip", req.getRemoteAddr());
            RpcContext.getContext().setAttachments(attachments);
        }

        return  invoker.invoke(invocation);
    }
}
